﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using MiniExcelLibs;
using thinger.MTHModels;

namespace thinger.MTHProject
{
    public partial class FrmGroupConfig : Form
    {
        public FrmGroupConfig()
        {
            InitializeComponent();
            //配置存储区
            this.cbbStoreArea.DataSource = new List<string>() { "输出线圈0x", "输入线圈1x", "输出寄存器4x", "输入寄存器3x" };
            //取消自动创建列
            this.dgvGroupList.AutoGenerateColumns = false;
            //加载数据
            DataLoad();
            //刷新数据
            Refresh();

        }
        //保存文件的路径
        private string groupPath = Application.StartupPath + "\\Config\\Group.xlsx";


        private List<Group> groupAll = new List<Group>();


        //保存通信组设置
        private void btnAdd_Click(object sender, EventArgs e)
        {

            try
            {

                if (groupAll.Find(a => a.GroupName == this.textGroupName.Text.ToString()) == null)
                {
                    Group group = new Group()
                    {
                        GroupName = this.textGroupName.Text,
                        Start = (ushort)this.nUpStart.Value,
                        Length = (ushort)this.nUpLength.Value,
                        StoreArea = this.cbbStoreArea.Text,
                        Remark = this.textRemark.Text,
                    };

                    groupAll.Add(group);
                    //保存在文件中
                    MiniExcel.SaveAs(groupPath, groupAll, overwriteFile: true);

                    new FrmMsgBoxWithOutAck("通信组添加", "成功").Show();

                    //刷新数据
                    Refresh();
                }
                else
                {
                    new FrmMsgBoxWithOutAck("通信组添加失败", "通信组名已经存在").Show();
                }




            }
            catch (Exception ex)
            {
                new FrmMsgBoxWithOutAck("添加通信组配置失败", "添加失败").Show();
            }



        }

        private void DataLoad()
        {
            //建立目标目录
            string directoryName = Path.GetDirectoryName(groupPath);

            if (!Directory.Exists(directoryName))
            {
                Directory.CreateDirectory(directoryName);
            }
            try
            {
                List<Group> groups = MiniExcel.Query<Group>(groupPath).ToList();
                if (groups.Count > 0)
                {
                    groupAll = groups;
                }

            }
            catch (Exception)
            {

                return;
            }


        }

        private void Refresh()
        {
            if (groupAll.Count > 0 && groupAll != null)
            {
                this.dgvGroupList.DataSource = null;
                this.dgvGroupList.DataSource = groupAll;
            }




        }


        private void btnCanel_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            try
            {
                Group group = groupAll.Find(a => a.GroupName == this.textGroupName.Text.Trim());
                if (group != null)
                {

                    DialogResult dialogResult = new FrmMsgBoxWithAck("是否确定删除", "删除通信组" + group.GroupName).ShowDialog();
                    if (dialogResult == DialogResult.OK)
                    {
                        groupAll.Remove(group);
                        MiniExcel.SaveAs(groupPath, groupAll, overwriteFile: true);
                        //刷新数据
                        Refresh();
                    }

                }
                else
                {
                    new FrmMsgBoxWithOutAck("删除错误", "不存在相关的通信组").Show();
                }
            }
            catch (Exception ex)
            {

                new FrmMsgBoxWithOutAck("删除错误", "通信组删除错误" + ex.Message).Show();
            }

        }

        private void btnUpdate_Click(object sender, EventArgs e)
        {
            try
            {
                Group group = groupAll.Find(a => a.GroupName == this.textGroupName.Text.Trim());
                if (group != null)
                {
                    group.GroupName = this.textGroupName.Text;
                    group.Start = (ushort)this.nUpStart.Value;
                    group.Length = (ushort)this.nUpLength.Value;
                    group.StoreArea = this.cbbStoreArea.Text;
                    group.Remark = this.textRemark.Text;

                    MiniExcel.SaveAs(groupPath, groupAll, overwriteFile: true);

                    //刷新数据
                    Refresh();
                }
                else
                {
                    new FrmMsgBoxWithOutAck("更新的通信组不存在", "请先添加通信组").Show();

                }
            }
            catch (Exception ex)
            {

                new FrmMsgBoxWithOutAck("更新错误", "更新错误" + ex.Message).Show();
            }



        }


        #region 无边框拖动
        private Point mPoint;
        private void Panel_MouseDown(object sender, MouseEventArgs e)
        {
            mPoint = new Point(e.X, e.Y);
        }
        private void Panel_MouseMove(object sender, MouseEventArgs e)
        {
            //鼠标左键点击
            if (e.Button == MouseButtons.Left)
            {
                this.Location = new Point(this.Location.X + (e.X - mPoint.X), this.Location.Y + (e.Y - mPoint.Y));
            }

        }
        #endregion

        #region 设置自动索引
        private void dgvGroupList_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            Rectangle rectangle = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y, this.dgvGroupList.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(), this.dgvGroupList.RowHeadersDefaultCellStyle.Font, rectangle, this.dgvGroupList.RowHeadersDefaultCellStyle.ForeColor, TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }
        #endregion

        #region 给空白的数据加“---”
        private void dgvGroupList_CellFormatting(object sender, DataGridViewCellFormattingEventArgs e)
        {
            if (e.ColumnIndex >= 0 && e.RowIndex >= 0)
            {
                object value = this.dgvGroupList.Rows[e.RowIndex].Cells[e.ColumnIndex].Value;

                if (value == null || value.ToString().Length == 0)
                {
                    e.Value = "---";
                }
            }
        }
        #endregion
        /// <summary>
        /// 点击单元格，做回溯
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void dgvGroupList_CellClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
            {
                Group group = groupAll[e.RowIndex];

                this.textGroupName.Text = group.GroupName.ToString();
                this.nUpStart.Value = group.Start;
                this.nUpLength.Value = group.Length;
                this.cbbStoreArea.Text = group.StoreArea.ToString();
                this.textRemark.Text = group.Remark.ToString();
            }
        }
    }
}
